<template>
  <view class="order-detail app-container" style="overflow: hidden">
    <view class="flex-1" style="overflow-y: auto">
      <view class="bg-white p-40">
        <view class="field mb-20">
          <view class="label">订单编号</view>
          <view class="value">{{ detail.code }}</view>
        </view>
        <view class="field mb-20">
          <view class="label">下单时间</view>
          <view class="value">{{ detail.created_at }}</view>
        </view>
        <view class="field mb-20">
          <view class="label">下单门店</view>
          <view class="value">{{ detail.merchant.name }}</view>
        </view>
        <!-- <view class="field">
        <view class="label">支付方式</view>
        <view class="value">{{ detail.code }}</view>
      </view> -->
      </view>
      <view class="main p-20">
        <!-- <view class="my-card mb-20" v-if="detail.status == 'canceled'">
          <u-icon
            name="info-circle-fill"
            label="取消原因"
            size="24"
            label-size="18"
          ></u-icon>
          <u-gap height="10"></u-gap>
          <u-text type="info" text="超时未支付"></u-text>
        </view> -->

        <view class="my-card mb-20" v-if="detail.deliver">
          <u-icon name="map" label="收货信息" size="24" label-size="18"></u-icon>
          <u-gap height="10"></u-gap>
          <u-text :text="detail.deliver.name + ' ' + detail.deliver.phone" bold></u-text>
          <u-gap height="10"></u-gap>
          <u-text type="info" :text="detail.deliver.address"></u-text>
        </view>

        <view v-for="(order, index) in detail.sub_orders" class="order-card" :key="index">
          <view class="order-card-top">
            <view class="top-title">
              <up-icon name="bag-fill" size="22" color="#ffffff"></up-icon>
              <view class="title">
                <text>{{ order.supplier.name }}</text>
                <text style="margin-left: 10rpx;">(运费:
                  {{ Number(order.express_amount) > 0 ? `￥${order.express_amount}` : '包邮' }})</text>
              </view>
            </view>
            <view class="goods-qty">{{ formatGoodsCountText(order) }}</view>
          </view>
          <view class="line-list">
            <block v-for="(item, index) in order.lines" :key="index">
              <view class="line-item" v-if="(!moreGoods && index <= 2) || moreGoods">
                <up-image width="80" height="80" radius="10" :src="item.product.image_url" :lazy-load="true"></up-image>
                <view class="line-item-right">
                  <view class="goods-name">{{ item.product.name }}</view>
                  <view class="goods-qty">x {{ item.quantity }}</view>
                  <view class="goods-qty">
                    {{
                      item.variant.attributes
                        .map((i) => `${i.key}:${i.value}`)
                        .join(";")
                    }}
                  </view>
                  <view class="goods-price">
                    <text class="price">￥{{ item.variant.sale_price }}</text>
                    <text class="unit">/{{ item.product.uom.name }}</text>
                  </view>
                </view>
              </view>
            </block>
          </view>
          <view class="more-btn" v-if="detail.lines.length > 3" @click="onMoreGoods">
            <text>{{ moreGoods ? "收起" : "查看全部" }}</text>
            <view class="more-icon" :class="{ open: moreGoods }">
              <up-icon name="arrow-down" size="14" color="#3cb9ef"></up-icon>
            </view>
          </view>
        </view>

        <view class="my-card mb-20">
          <u-icon name="rmb-circle-fill" label="订单金额" size="24" label-size="18"></u-icon>
          <u-cell-group :border="false">
            <u-cell title="标准价格" :value="`￥${standPrice}`"></u-cell>
            <u-cell title="运费合计" :value="`￥${expressAmount}`"></u-cell>
            <u-cell :border="false" title="实付" :value="`￥${totalPrice}`"></u-cell>
          </u-cell-group>
        </view>

        <view class="my-card mb-20">
          <u-icon name="info-circle-fill" label="订单备注" size="24" label-size="18"></u-icon>
          <view class="order-notes">
            <up-textarea v-model="detail.remark" placeholder="留言选填，100字以内" disabled count maxlength="100"
              height="100"></up-textarea>
          </view>
        </view>
      </view>
    </view>

    <view class="actions" v-if="isShowCancelButton || isShowAftercareButton">
      <template v-if="isShowCancelButton">
        <u-button type="info" @click="handleCancelOrder">取消订单</u-button>
        <u-button type="primary" @click="handlePay" :loading="payLoading">
          去支付
        </u-button>
      </template>
      <template v-if="isShowAftercareButton">
        <u-button type="error" @click="toApplyAftercare">申请售后</u-button>
      </template>
    </view>
  </view>
</template>

<script setup>
import {
  orderDetail,
  wechatPayInfo,
  cancelWechatPayOrder,
  payOrderStatus,
} from "@/common/apis/order.js";
import { onShow } from "@dcloudio/uni-app";
import { reactive, ref, computed } from "vue";
import { useStore } from "vuex";

const store = useStore();

const props = defineProps({
  id: String,
});

const moreGoods = ref(false);

const payLoading = ref(false);

const detail = reactive({
  code: "",
  created_at: "",
  customer_address: "",
  customer_name: "",
  customer_phone: "",
  express_amount: "",
  id: 0,
  is_active: false,
  lines: [],
  deliver: {},
  merchant: { id: 0, name: "" },
  payment: {},
  remark: "",
  status: "pending",
  supplier: { id: 0, name: "" },
  total_price: "",
  total_stand_price: "",
  updated_at: "",
  sub_orders: []
});

const formatGoodsCountText = computed(() => (order) => {
  let totalCount = 0;
  order.lines.forEach((i) => {
    totalCount += i.quantity;
  });
  return `${order.lines.length}种${totalCount}件`;
});

const isShowCancelButton = computed(() => {
  return detail.status == "pending";
});

const isShowAftercareButton = computed(() => {
  return detail.status == "paid" || detail.status == "express";
});

// 商品合计金额，通过计算属性计算
const standPrice = computed(() => {
  return Number(detail.total_stand_price).toFixed(2);
});

// 运费
const expressAmount = computed(() => {
  return Number(detail.express_amount).toFixed(2);
});

// 订单合计金额，目前等于商品合计金额
const totalPrice = computed(() => {
  return Number(detail.payment_amount).toFixed(2);
});

function onMoreGoods() {
  moreGoods.value = !moreGoods.value;
}

async function fetchOrderDetail() {
  const response = await orderDetail(props.id);
  if (response) {
    if (response.lines.length > 0) {
      response.sub_orders = [response];
    }
    Object.assign(detail, response);
  }
  return response;
}

// 取消订单
async function handleCancelOrder() {
  uni.showModal({
    title: "提示",
    content: "是否继续取消此订单",
    success: async (res) => {
      if (res.confirm) {
        const response = await store.dispatch("fetchCancelOrder", props.id);
        if (response) {
          uni.$u.toast("已取消");
          fetchOrderDetail();
        }
      }
    },
  });
}

// 微信小程序支付
function fetchWechatPay(out_trade_no) {
  console.log(out_trade_no);
  return new Promise((resolve, reject) => {
    uni.login({
      success: async (res) => {
        try {
          const { data: payInfo } = await wechatPayInfo({
            out_trade_no,
            code: res.code,
          });
          if (payInfo) {
            uni.requestPayment({
              provider: "wxpay",
              package: payInfo.package,
              nonceStr: payInfo.nonceStr,
              signType: payInfo.signType,
              timeStamp: payInfo.timeStamp,
              paySign: payInfo.paySign,
              orderInfo: payInfo,
              success: resolve,
              fail: async (err) => {
                console.log(err);
                await cancelWechatPayOrder({ out_trade_no });
                uni.$u.toast("支付失败");
                reject(err);
              },
            });
          } else {
            reject();
          }
        } catch (err) {
          reject(err);
        }
      },
    });
  });
}

async function handlePay() {
  payLoading.value = true;
  uni.showLoading();
  try {
    const result = await store.dispatch("fetchAddPayOrder", props.id);
    console.log(result.data.out_trade_no);
    if (result.data) {
      await fetchWechatPay(result.data.out_trade_no);
      await fetchOrderDetail();
    }
    payLoading.value = false;
    uni.hideLoading();
  } catch (err) {
    payLoading.value = false;
    uni.hideLoading();
  }
}

function toApplyAftercare() {
  uni.$u.route({
    url: "/pages/order/aftercare/apply",
    params: {
      id: props.id,
    },
  });
}

async function fetchPayOrderStatus() {
  await payOrderStatus({
    out_trade_no: detail.payment.out_trade_no,
  });
}

onShow(async () => {
  await fetchOrderDetail();
  await fetchPayOrderStatus();
  await fetchOrderDetail();
});
</script>

<style lang="scss" scoped>
.field {
  display: flex;

  .label {
    width: 6em;
    color: $u-info;
  }
}

.order-group-box {
  border-radius: 20rpx;
  overflow: hidden;
  background-color: #fff;

  .title {
    background-color: $u-primary;
    padding: 20rpx;
  }
}

.order-card {
  border-radius: 20rpx;
  overflow: hidden;
  background-color: #ffffff;
  margin-bottom: 20rpx;

  .order-card-top {
    padding: 20rpx;
    background-color: $u-primary;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .top-title {
      display: flex;
      align-items: center;

      .title {
        font-size: 30rpx;
        font-weight: bold;
        margin-left: 6rpx;
        color: #ffffff;
      }
    }

    .goods-qty {
      font-size: 28rpx;
      font-weight: bold;
      color: #ffffff;
    }
  }

  .line-list {
    padding: 0 20rpx;

    .line-item {
      padding: 20rpx 0;
      border-bottom: 2rpx solid #f0f0f0;
      display: flex;
      justify-content: space-between;

      .line-item-right {
        margin-left: 20rpx;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        flex: 1;
        padding: 10rpx 0;

        .goods-name {
          font-size: 30rpx;
          font-weight: bold;
          margin-bottom: 10rpx;
        }

        .price {
          font-size: 32rpx;
          font-weight: bold;
          color: #ff0000;
        }

        .goods-qty {
          font-size: 24rpx;
          color: #999999;
        }
      }
    }

    & .line-item:last-child {
      border-bottom: 0;
    }
  }

  .more-btn {
    color: #3cb9ef;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20rpx 0;

    .more-icon {
      margin-left: 10rpx;
      transition: all ease 0.5s;

      &.open {
        transform: rotateZ(-180deg);
      }
    }
  }

  .order-notes {
    border-top: 2rpx solid #f0f0f0;
    padding: 20rpx;

    .notes-title {
      font-size: 30rpx;
      font-weight: bold;
      margin-bottom: 20rpx;
    }
  }
}

.actions {
  display: flex;
  align-items: center;
  padding: 20rpx 20rpx calc(20rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;
  background-color: #fff;
  gap: 20rpx;
}

.order-notes {
  padding: 20rpx;

  .notes-title {
    font-size: 30rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
}
</style>
